package com.sim.stream.service.impl;

import com.sim.core.ImConst;
import com.sim.core.cache.redis.JedisTemplate;
import com.sim.stream.service.StreamService;
import com.sim.stream.util.ShellUtil;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 混流方案
 * @author yzf
 */
@Service
public class MixedStreamServiceImpl implements StreamService {
    private static final Logger LOG = LoggerFactory.getLogger(StreamServiceImpl.class.getName());

    @Resource
    private ShellUtil shellUtil;

    @Override
    public void publish(Map<String, String> map) {
        try{
            String rtmpUrl = map.get("domain");
            String name = map.get("name");
            Pair<String,String> groupUser = shellUtil.getGroupAndUser(name);
            String groupId = groupUser.getLeft();
            String userId = groupUser.getRight();
            //如果是个人或合并后的流,不作任何处理
            if(groupId.equals(userId)){
                return;
            }
            JedisTemplate me = JedisTemplate.me();
            String groupKey = ImConst.STREAM + ImConst.SUFFIX + groupId + ImConst.SUFFIX + ImConst.USER;
            List<String> users = me.listGetAll(groupKey);
            if(!users.contains(userId)){
                me.listPushTail(groupKey,userId);
                users.add(userId);
            }
            shellUtil.ffmpegCommand(groupId, users,rtmpUrl);

        }
        catch (Exception e){
            LOG.error("rtmp stream publish handle exception,reason:{}",e.toString());
        }
    }

    @Override
    public void publishDone(String requestStr) {
        try {
            Map<String, String> map = shellUtil.decodeRequestBody(requestStr);
            String name = map.get("name");
            Pair<String, String> groupUser = shellUtil.getGroupAndUser(name);
            String groupId = groupUser.getLeft();
            String userId = groupUser.getRight();
            String groupKey = ImConst.STREAM + ImConst.SUFFIX + groupId + ImConst.SUFFIX + ImConst.USER;
            JedisTemplate me = JedisTemplate.me();
            me.listRemove(groupKey, 0, userId);
            List<String> users = me.listGetAll(groupKey);
            shellUtil.ffmpegCommand(groupId, users, map.get("tcurl"));
        }
        catch (Exception e){
            LOG.error("rtmp stream publish end handle exception,reason:{}",e.toString());
        }
    }

    @Override
    public void play(String requestStr) {

    }

    @Override
    public void playDone(String requestStr) {

    }


}
